package com.jweb.framework.id;

import java.sql.Connection;
import java.sql.SQLException;


public class TableSequenceFactory extends AbstractSequenceFactory {
	
	private int retryCount = 20 ; //
	SequenceTable table ; // 
	boolean  dateCutoff   ; // 
	boolean  autoCommit = true  ; // 
	private String corpId;
	
	public String getCorpId() {
        return corpId;
    }

    public void setCorpId(String corpId) {
        this.corpId = corpId;
    }

    public void setTable(SequenceTable table){
		this.table = table ;
	}
	
	public void setRetryCount(int i){
		this.retryCount = i ;
	}
	
	public void setAutoCommit(boolean flag){
		this.autoCommit = flag ;
	}
	
	public void setDateCutoff(boolean flag){
		this.dateCutoff = flag ;
	}
	
	public String getDepartId(){
	   
	    return corpId.substring(2);
	}
	
	protected long[] internalGenerate(int sequ,String corpId) {
	    this.corpId = corpId;
        try {
            Connection conn = this.table.getConnection() ;
            boolean flag = conn.getAutoCommit() ;
            try {
                if(!this.autoCommit){
                    conn.setAutoCommit(false);
                }
                int i = 0 ;
                long[] arr = null ;
                for(int j = 0 ; (j < this.retryCount) && (i != 1) ; j++){
                    try {
                        arr = this.table.doSelect(conn, this.type , this.dateCutoff, corpId);
                        if(arr[0] == -1L){
                            this.table.doInsert(conn, this.type , 0L , arr[1], corpId);
                            arr[0] = 0L ;
                        }
                        
                        i = this.table.doupdate(conn, this.type , sequ , arr[1] , arr[0], corpId);
                    } catch (SQLException e) {
                        this.logger.warn("get id retry: " + j + ", cause:" + e);
                        if(j == (this.retryCount -1)){
                            throw e ;
                        }
                    }
                }
                if(i != 1){
                    throw new IllegalStateException("cannot get id");
                }
                
                if(!this.autoCommit){
                    conn.commit();
                }
                
                return arr ;
                
            } catch (SQLException ex) {
                if(!this.autoCommit){
                    conn.rollback() ;
                }
                throw ex ;
            } finally {
                if(!this.autoCommit){
                    conn.setAutoCommit(flag);
                }
                conn.close() ;
            }
        } catch (SQLException ex1) {
            throw new IllegalStateException(ex1);
        }
    }
	
}
